import { useState, useCallback } from 'react';

interface PaginationState {
  current: number;
  pageSize: number;
  total: number;
}

interface UsePaginationOptions {
  initialPage?: number;
  initialPageSize?: number;
  initialTotal?: number;
}

export const usePagination = (options: UsePaginationOptions = {}) => {
  const {
    initialPage = 1,
    initialPageSize = 20,
    initialTotal = 0
  } = options;

  const [pagination, setPagination] = useState<PaginationState>({
    current: initialPage,
    pageSize: initialPageSize,
    total: initialTotal,
  });

  const updatePagination = useCallback((updates: Partial<PaginationState>) => {
    setPagination(prev => ({ ...prev, ...updates }));
  }, []);

  const setPage = useCallback((page: number) => {
    setPagination(prev => ({ ...prev, current: page }));
  }, []);

  const setPageSize = useCallback((pageSize: number) => {
    setPagination(prev => ({ ...prev, pageSize, current: 1 }));
  }, []);

  const setTotal = useCallback((total: number) => {
    setPagination(prev => ({ ...prev, total }));
  }, []);

  const reset = useCallback(() => {
    setPagination({
      current: initialPage,
      pageSize: initialPageSize,
      total: initialTotal,
    });
  }, [initialPage, initialPageSize, initialTotal]);

  const getTablePaginationConfig = useCallback(() => ({
    current: pagination.current,
    pageSize: pagination.pageSize,
    total: pagination.total,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number, range: [number, number]) => 
      `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
    onChange: (page: number, pageSize?: number) => {
      updatePagination({
        current: page,
        pageSize: pageSize || pagination.pageSize,
      });
    },
  }), [pagination, updatePagination]);

  return {
    pagination,
    updatePagination,
    setPage,
    setPageSize,
    setTotal,
    reset,
    getTablePaginationConfig,
  };
};
